package io.eyer.zookeeper;

import io.eyer.cluster.proxy.ZookeeperServerProxy;
import io.eyer.nio.core.event.Acceptor;
import io.eyer.nio.core.event.ReactorPool;
import io.eyer.nio.core.support.NioConfig;
import io.eyer.rpc.codec.KeyoCodec;
import io.eyer.rpc.handler.ServerHandler;
import io.eyer.service.RemoteUserService;
import io.eyer.service.UserService;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Created by 青木 on 2015/8/31.
 */
public class ZookeeperServer {

    public static void main(String[] args) throws IOException {
        NioConfig.registered(new KeyoCodec());
        final ServerHandler invocationHandler = new ServerHandler();
        NioConfig.registered(invocationHandler);
        NioConfig.initSessionHandler();
        NioConfig.initSessionHandler();
        Acceptor acceptor = new Acceptor(new ReactorPool(1));
        acceptor.start();
        ZookeeperServerProxy zookeeperServerProxy = new ZookeeperServerProxy(getIp(), 6363, acceptor, "192.168.1.66:2181");
        zookeeperServerProxy.exportService(UserService.class, new RemoteUserService());
        zookeeperServerProxy.start();
    }

   static String getIp() throws UnknownHostException {
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                if (ni.getName().equals("eth0")){
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        System.out.println("IP:"  + ips.nextElement().getHostAddress());
                        String  ipTemp= ni.getInetAddresses().nextElement().getHostAddress();
                        if(ipTemp!="127.0.0.1" && !"127.0.0.1".equals(ipTemp))
                        {
                            return ipTemp;
                        }
                    }
                }

            }
        }catch(Exception ee)
        {
            ee.printStackTrace();
        }
        return InetAddress.getLocalHost().getHostAddress();
    }
}
